package com.wq.payunion.oauth2.useroauth2.oauth2;

import com.google.gson.Gson;
import com.wq.payunion.oauth2.useroauth2.constant.AuthorizationConfig;
import com.wq.payunion.oauth2.useroauth2.model.AbstractOAuthBean;
import com.wq.payunion.oauth2.useroauth2.model.AccessTokenParam;
import com.wq.payunion.oauth2.useroauth2.model.OAuthInfoParam;
import com.wq.payunion.oauth2.useroauth2.model.OAuthResult;
import com.wq.payunion.oauth2.useroauth2.model.baidu.BaiduAccessTokenParam;
import com.wq.payunion.oauth2.useroauth2.model.baidu.BaiduCodeBean;
import com.wq.payunion.oauth2.useroauth2.utils.HttpCommunication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: wangqiang20995
 * @Date:2018 年 9 月 15 日 0015
 * @Description:
 * @Resource:
 */
@Service(value = "baiduOAuth")
public class BaiduOAuthService implements ThirdSystemOAuth {

    @Autowired
    private AuthorizationConfig authorizationConfig;

    @Autowired
    private HttpCommunication communication;

    private Gson gson = new Gson();//这么做可能存在并发问题

    private Logger logger = LoggerFactory.getLogger(getClass());

    public AuthorizationConfig getAuthorizationConfig() {
        return authorizationConfig;
    }

    public void setAuthorizationConfig(AuthorizationConfig authorizationConfig) {
        this.authorizationConfig = authorizationConfig;
    }

    public HttpCommunication getCommunication() {
        return communication;
    }

    public void setCommunication(HttpCommunication communication) {
        this.communication = communication;
    }

    @Override
    public OAuthResult generatorRedirectUrl(AbstractOAuthBean param, String extract) {
        param = gson.fromJson(extract,BaiduCodeBean.class);
        String requestExtractParams = this.buildCodeRequest((BaiduCodeBean) param);
        OAuthResult oAuthResult = new OAuthResult();
        oAuthResult.setSuccessFlag(true);
        oAuthResult.setCallInfo("鉴权接口地址重定向组装成功");
        oAuthResult.setResponse("redirectUrl", authorizationConfig.getBaiduAuthorizeUrl() + "?" + requestExtractParams);
        oAuthResult.setUuid(param.getUuid());
        return oAuthResult;
    }

    @Override
    public Map<String, Object> accessToken(AccessTokenParam accessTokenParam, String params) {
        BaiduAccessTokenParam baiduAccessTokenParam = gson.fromJson(params,BaiduAccessTokenParam.class);
        Map<String,String> param = new HashMap<>();
        param.put("grant_type","authorization_code");
        param.put("code",baiduAccessTokenParam.getCode());
        param.put("client_id",authorizationConfig.getBaiduClientId());
        param.put("client_secret",authorizationConfig.getBaiduClientSecret());
        param.put("redirect_uri",baiduAccessTokenParam.getRedirect_uri());

        String response = this.communication.doFullTrustHttpsPostRequest(authorizationConfig.getBaiduAccessToken(),param);
        Map<String,Object> resultMap = gson.fromJson(response,Map.class);

        return resultMap;
    }

    @Override
    public Map<String, Object> oauthWithAccessToken(OAuthInfoParam param) {
        String json = this.communication.doFullTrustHttpsPostRequest(authorizationConfig.getLoggerInUser(),param.getExtractParams());

        return gson.fromJson(json,Map.class);
    }

    private String buildCodeRequest (BaiduCodeBean baiduCodeBean){
        StringBuilder builder = new StringBuilder();
        builder.append("client_id=").append(authorizationConfig.getBaiduClientId()).append("&");
        builder.append("response_type=").append("code").append("&");
        builder.append("redirect_uri=").append(authorizationConfig.getCallbackUrl()).append("&");
        builder.append("scope=").append(StringUtils.isEmpty(baiduCodeBean.getScope()) ? "" : baiduCodeBean.getScope()).append("&");
        String uuid = UUID.randomUUID().toString().replaceAll("\\-","");
        baiduCodeBean.setUuid(uuid);
        builder.append("state=").append(uuid).append("&");
        builder.append("display=").append(StringUtils.isEmpty(baiduCodeBean.getDisplay()) ? "" : baiduCodeBean.getDisplay()).append("&");
        builder.append("force_login=").append(StringUtils.isEmpty(baiduCodeBean.getForce_login()) ? "" : baiduCodeBean.getForce_login()).append("&");
        builder.append("confirm_login=").append("").append("&");
        builder.append("login_type=").append("");

        return builder.toString();
    }
}
